package com.zndroid.notification.policy;

import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.widget.RemoteViews;

import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;
import androidx.core.content.res.ResourcesCompat;

import com.zndroid.notification.assist.IconUtilities;
import com.zndroid.notification.box.Trumpet;

/**
 * 具体展示类
 * @author lzy
 * @date 2021/2/9
 */
public final class Delegate {
    private final String TAG = "Notifier --> ";

    private @NonNull Context context;
    private @NonNull Trumpet trumpet;
    private NotificationManager manager;

    public Delegate(@NonNull Context context, @NonNull Trumpet trumpet) {
        this.context = context;
        this.trumpet = trumpet;
        this.manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        magic();
    }

    /**
     * NotificationChannel 的配置会覆盖 NotificationCompat.Builder 的配置
     * 在使用了 NotificationChannel 之后，关于震动、声音、呼吸灯的设置都需要在 NotificationChannel 中进行设置
     * 通过查看源码：通过 isPreChannelsNotification()方式进行拦截的
     * return true when 'applicationInfo.targetSdkVersion < Build.VERSION_CODES.O'
     * */
    @TargetApi(Build.VERSION_CODES.O)
    private void showAPI26_() {
        NotificationChannel channel = new NotificationChannel(
                trumpet.getChannelId(), trumpet.getChannelName(), NotificationManager.IMPORTANCE_HIGH);
        channel.canBypassDnd();//是否绕过请勿打扰模式
        channel.enableLights(true);//闪光灯
        channel.setLockscreenVisibility(Notification.VISIBILITY_SECRET);//锁屏显示通知
        channel.setLightColor(Color.RED);//闪关灯的灯光颜色
        channel.canShowBadge();//桌面launcher的消息角标
        channel.enableVibration(true);//是否允许震动
        channel.setBypassDnd(true);//设置可绕过  请勿打扰模式
        channel.setVibrationPattern(new long[]{100, 100, 200});//设置震动模式
        channel.shouldShowLights();//是否会有灯光

        if (trumpet.isSoundEnable()) {
            channel.setSound(trumpet.getSoundUri(), Notification.AUDIO_ATTRIBUTES_DEFAULT);
        }

        manager.createNotificationChannel(channel);
        manager.notify(trumpet.getId(), createNotification());
    }

    private void showAPI_25() {
        manager.notify(trumpet.getId(), createNotification());
    }

    private Notification createNotification() {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, trumpet.getChannelId());
        builder.setChannelId(trumpet.getChannelId());
        builder.setContentTitle(trumpet.getTitle());
        builder.setContentText(trumpet.getMessage());
        builder.setShowWhen(true);
        builder.setWhen(System.currentTimeMillis());
        builder.setLargeIcon(trumpet.getBigIcon());
        builder.setSmallIcon(trumpet.getSmallIcon());
        builder.setAutoCancel(true);
        builder.setStyle(new NotificationCompat.BigTextStyle().bigText(trumpet.getMessage()));
        builder.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(trumpet.getBigPicture()));
        builder.setLocalOnly(false);
        builder.setContentIntent(trumpet.getActionPending());
        builder.setDeleteIntent(trumpet.getDeletePending());
        builder.setDefaults(trumpet.getDefaults());
        builder.setOngoing(trumpet.isOnGoing());
        builder.setPriority(trumpet.getPriority());

        if (null != trumpet.getRemoteViews()) {
            builder.setContent(trumpet.getRemoteViews());
        }

        //是否静默
        if (trumpet.isSilentEnable()) {
            builder.setNotificationSilent();
        }

        return builder.build();
    }

    public void show() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            showAPI26_();
        } else {
            showAPI_25();
        }
    }

    private void magic() {
        //inner compatibility

        ////id
        if (-1 >= trumpet.getId()) {
            throw new IllegalArgumentException(TAG + "id not allow negative.");
        }

        ////smallIcon
        if (-1 >= trumpet.getSmallIcon()) {
            throw new IllegalArgumentException(TAG + "small icon id not allow negative or not found.");
        }

        ////BigIcon need Bitmap
        if (null == trumpet.getBigIcon()) {
            //未设置bitmap
            IconUtilities iconUtilities = new IconUtilities(context);
            if (-1 != trumpet.getBigIconRes()) {
                trumpet.setBigIcon(iconUtilities.createIconBitmap(ResourcesCompat.getDrawable(context.getResources(), trumpet.getBigIconRes(), context.getTheme())));
            } else {
                final PackageManager pm = context.getPackageManager();
                final ApplicationInfo aInfo = getApplicationInfo(pm, context.getPackageName());
                final Drawable drawable = pm.getApplicationIcon(aInfo);
                if (drawable != null) {
                    trumpet.setBigIcon(iconUtilities.createIconBitmap(drawable));
                }
            }
        }

        ////remoteViews
        if (null == trumpet.getRemoteViews()) {
            if (-1 < trumpet.getRemoteLayoutId()) {
                RemoteViews remoteViews = new RemoteViews(context.getPackageName(), trumpet.getRemoteLayoutId());
                trumpet.setRemoteViews(remoteViews);
            }
        }
    }

    public RemoteViews getRemoteViews() {
        return trumpet.getRemoteViews();
    }

    private ApplicationInfo getApplicationInfo(PackageManager pm, String packageName) {
        try {
            return pm.getApplicationInfo(packageName, 0);
        } catch (PackageManager.NameNotFoundException e) {
            return null;
        }
    }
}
